import { useStore } from '@/hooks';
import { CascaderSelect, Form } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import React, { useEffect } from 'react';

const AreaCascader = (props) => {
  const { name, value = [], type, record, ...cfg } = props;
  const { orderChangeStore: store } = useStore();
  useEffect(() => {
    if (value.length !== 0) {
      (async () => {
        const { beginArea = '', endArea = '' } = record || {};
        const [beginMain] = beginArea.split('-');
        const [endMain] = endArea.split('-');
        const fromCity = type === 'begin' ? '' : beginMain;
        const city = type === 'begin' ? beginMain : endMain;
        await store.getCities(fromCity, type);
        if (city) {
          await store.getAreas(fromCity, city, type);
        }
      })();
    }
  }, [value, type]);

  return (
    <Form.Item name={name} {...cfg?.itemProps} {...cfg?.itemLayout}>
      <CascaderSelect
        value={toJS(value)}
        dataSource={toJS(store.options.area[type])}
        loadData={async (v) => {
          const { value: city } = v;
          await store.getAreas('', city, type);
        }}
      />
    </Form.Item>
  );
};

export default observer(AreaCascader);
